package com.example.mq;

import com.example.vo.VideoVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;

/*
 * @Author: hx
 * @CreateTime: 2022/3/8 13:41
 * @Description:
 * */
@Component
@Slf4j
public class VideoConsumer {
    @Qualifier("elasticsearchClient")
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue,
            exchange = @Exchange(name = "videos",type = "fanout")
    ))
    public void receive(String message) throws IOException {
        log.info("MQ接受到的video信息为：{}",message);
        //将mq中的video的json格式转换为videoVo对象
        VideoVO videoVO = new ObjectMapper().readValue(message, VideoVO.class);
        //2.创建ES中索引请求对象  参数1:操作索引  参数2:操作类型  参数3:文档id
        IndexRequest indexRequest = new IndexRequest("video", "video", videoVO.getId().toString());
        //3.设置ES文档的内容
        indexRequest.source(message, XContentType.JSON);
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        log.info("video录入的信息状态为{}",indexResponse.status());
    }
}
